﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Data;
using SmartProject.BusinessObjects;

namespace SmartProject.AppSpace.WebControls
{
    public partial class WorkGridView : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CtlAddEditWork.Initialize(null);
            }
        }

        protected void BtnView_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            Cache["WorkID"] = btn.CommandArgument;
            Response.Redirect("~/AppSpace/Work.aspx", true);
        }

        protected void BtnGo_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            Cache["WorkID"] = btn.CommandArgument;
            Response.Redirect("~/AppSpace/Work.aspx", true);
        }

        protected void BtnDelete_Click(object sender, EventArgs e)
        {
            Work work = new Work();
            ImageButton btn = (ImageButton)sender;
            work.SetAttribute("WorkId", btn.CommandArgument);
            work.Remove();
            RefreshView();
        }

        public void RefreshView()
        {
            RefreshView(Convert.ToBoolean(this.PlcEditMode.Value));
        }

        public void RefreshView(bool editMode)
        {
            this.PlcEditMode.Value = editMode.ToString();
            UI.IDataSourcePage dataSource = (UI.IDataSourcePage)this.Page;

            Work work = new Work();
            this.LstWorkItems.DataSource = dataSource.DataSource;
            this.LstWorkItems.DataBind();

            if (this.LstWorkItems.DataSource != null)
            {
                Sprint sprint = new Sprint();
                SmartProject.BusinessObjects.User user = new SmartProject.BusinessObjects.User();
                for (int i = 0; i < this.LstWorkItems.Items.Count; i++)
                {
                    ListViewDataItem cellDetails = this.LstWorkItems.Items[i];

                    HtmlInputHidden plcWorkId = (HtmlInputHidden)cellDetails.FindControl("PlcWorkId");
                    Label lblWorkId = (Label)cellDetails.FindControl("LblWorkId");
                    lblWorkId.Text = plcWorkId.Value;

                    HtmlInputHidden plcStatus = (HtmlInputHidden)cellDetails.FindControl("PlcStatusId");
                    Label lblStatus = (Label)cellDetails.FindControl("LblStatus");
                    lblStatus.Text = work.Statuses.GetValue(Convert.ToInt32(plcStatus.Value));

                    HtmlInputControl plcDueBy = (HtmlInputControl)cellDetails.FindControl("PlcDueDate");
                    Label lblDueBy = (Label)cellDetails.FindControl("LblDueBy");
                    DateTime dueBy = Convert.ToDateTime(plcDueBy.Value);

                    Label lblDueByDate = (Label)cellDetails.FindControl("LblDueByDate");
                    lblDueByDate.Text = dueBy.ToLongDateString();
                    TimeSpan length = dueBy - DateTime.Today;
                    int days = length.Days;
                    if (days == 0)
                    {
                        lblDueBy.ForeColor = System.Drawing.Color.Red;
                        lblDueByDate.ForeColor = System.Drawing.Color.Red;
                        lblDueBy.Text = "Due today.";
                    }
                    else if (days > 0)
                    {
                        lblDueBy.Text = String.Format("{0} days remaining.", days.ToString());
                    }
                    else if (days < 0)
                    {
                        lblDueBy.ForeColor = System.Drawing.Color.Red;
                        lblDueByDate.ForeColor = System.Drawing.Color.Red;
                        lblDueBy.Text = String.Format("Past due by {0} day(s).",
                            Math.Abs(days).ToString());
                    }

                    HtmlInputControl plcPriorityId = (HtmlInputControl)cellDetails.FindControl("PlcPriorityId");
                    work.Priorities.SetLabel((Label)cellDetails.FindControl("LblPriority"), plcPriorityId.Value);

                    Label lblDeveloper = (Label)cellDetails.FindControl("LblDeveloper");
                    Label lblSprintDesc = (Label)cellDetails.FindControl("LblSprintDescription");

                    Label lblEst = (Label)cellDetails.FindControl("LblEst");
                    HtmlInputControl estTimeTypeId = (HtmlInputControl)cellDetails.FindControl("PlcEstTimeTypeId");
                    if (!editMode)
                    {
                        if (String.IsNullOrEmpty(lblDeveloper.Text))
                        {
                            lblDeveloper.Text = "Unassigned";
                            lblDeveloper.ForeColor = System.Drawing.Color.Red;
                        }

                        if (String.IsNullOrEmpty(lblSprintDesc.Text))
                        {
                            lblSprintDesc.Text = "Unassigned";
                            lblSprintDesc.ForeColor = System.Drawing.Color.Red;
                        }

                        HtmlInputControl plcEstTime = (HtmlInputControl)cellDetails.FindControl("PlcEstTime");
                        if (String.IsNullOrEmpty(plcEstTime.Value))
                        {
                            lblEst.Text = "Unassigned";
                            lblEst.ForeColor = System.Drawing.Color.Red;
                        }
                        else
                        {
                            lblEst.Text = String.Format("{0} {1}", plcEstTime.Value,
                                work.EstTimeType.GetValue(Convert.ToInt32(estTimeTypeId.Value)));
                        }
                    }
                    else
                    {
                        lblDeveloper.Visible = false;
                        lblSprintDesc.Visible = false;
                        DropDownList drpDevelopers = (DropDownList)cellDetails.FindControl("DrpDevelopers");
                        drpDevelopers.Visible = true;

                        user.Populate(drpDevelopers);
                        drpDevelopers.Items.Insert(0, new ListItem("Select one", "0"));

                        DropDownList drpSprints = (DropDownList)cellDetails.FindControl("DrpSprints");
                        drpSprints.Visible = true;
                        sprint.Populate(drpSprints);
                        drpSprints.Items.Insert(0, new ListItem("Select one", "0"));

                        HtmlInputControl developerId = (HtmlInputControl)
                            cellDetails.FindControl("PlcDeveloperId");
                        if (!String.IsNullOrEmpty(developerId.Value))
                        {
                            drpDevelopers.SelectedValue = developerId.Value;
                        }

                        HtmlInputControl sprintId = (HtmlInputControl)cellDetails.FindControl("PlcSprintId");
                        if (!String.IsNullOrEmpty(sprintId.Value))
                        {
                            drpSprints.SelectedValue = sprintId.Value;
                        }

                        lblEst.Visible = false;

                        LinkButton btnSave = (LinkButton)cellDetails.FindControl("BtnSave");
                        btnSave.Visible = true;
                        TextBox txtEst = (TextBox)cellDetails.FindControl("TxtEst");
                        txtEst.Visible = true;
                        DropDownList drpEst = (DropDownList)cellDetails.FindControl("DrpEst");
                        drpEst.Visible = true;
                        work.EstTimeType.Populate(drpEst);
                        drpEst.Items.Insert(0, new ListItem("--Select one--", "0"));
                        if (!String.IsNullOrEmpty(estTimeTypeId.Value))
                        {
                            drpEst.SelectedValue = estTimeTypeId.Value;
                        }
                    }
                }
            }
        }

        protected void DrpDevelopers_SelectedIndexChanged(object sender, EventArgs e)
        {
            UI.BasePage page = (UI.BasePage)this.Page;
            page.ClearErrorOrWarning();

            DropDownList drpDevelopers = (DropDownList)sender;
            HtmlInputControl input = (HtmlInputControl)drpDevelopers.Parent.FindControl("PlcWorkId");
            Work work = new Work();
            work.SetAttribute("WorkId", input.Value);
            work.SetAttribute("DeveloperId", drpDevelopers.SelectedValue);
            try
            {
                work.UpdateDeveloper();
            }
            catch (Exceptions.BusinessRuleViolation ex)
            {
                page.DisplayErrorOrWarning(ex.Message);
                return;
            }
            RefreshView();
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            UI.BasePage page = (UI.BasePage)this.Page;
            page.ClearErrorOrWarning();

            LinkButton btnSave = (LinkButton)sender;
            DropDownList drpSprints = (DropDownList)btnSave.Parent.FindControl("DrpSprints");
            TextBox txtEst = (TextBox)btnSave.Parent.FindControl("TxtEst");
            DropDownList drpEst = (DropDownList)btnSave.Parent.FindControl("DrpEst");
            HtmlInputControl input = (HtmlInputControl)btnSave.Parent.FindControl("PlcWorkId");
            Work work = new Work();

            try
            {
                work.SetAttribute("WorkId", input.Value);
                work.SetAttribute("SprintId", drpSprints.SelectedValue);
                work.SetAttribute("EstTime", txtEst.Text);
                work.SetAttribute("EstTimeTypeId", drpEst.SelectedValue);
            }
            catch (Exceptions.RequiredDataParameter requiredDataParameter)
            {
                page.DisplayErrorOrWarning(requiredDataParameter.Message);
                return;
            }

            try
            {
                work.UpdateSprint();
            }
            catch (Exceptions.BusinessRuleViolation businessRuleViolation)
            {
                page.DisplayErrorOrWarning(businessRuleViolation.Message);
                return;
            }
            RefreshView();
        }

        public AjaxControlToolkit.ModalPopupExtender Popup
        {
            get { return this.PopupAddWork; }
        }
    }
}